﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Web.Caching;

namespace Webbshop
{
    public partial class StockStatus : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Om Produkterna inte finns i Cache, hämta dom.
                if(Cache.Get("Products") == null)
                    Cache.Insert("Products", Functions.GetProducts(), null, Cache.NoAbsoluteExpiration, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(OnRemove));
                
                BindData();     
            }
        }

        protected void gridOrders_RowEditing(object source, GridViewEditEventArgs e)
        {
            gridOrders.EditIndex = e.NewEditIndex; // Sätt gridView i edit-mode
            BindData();
        }

        protected void gridOrders_RowUpdating(object source, GridViewUpdateEventArgs e)
        {
            var newAmount = int.Parse(e.NewValues["stockStatus"].ToString());
            var productId = int.Parse(e.Keys["productId"].ToString());
            Functions.UpdateStockStatus(newAmount, productId);
            Cache.Remove("Products"); // Ta bort den gamla datan (uppdatering sker automagiskt)
            gridOrders.EditIndex = -1; // Hoppa ur edit-mode
            BindData();
        }

        protected void gridOrders_RowCancelingEdit(object source, GridViewCancelEditEventArgs e)
        {
            gridOrders.EditIndex = -1; // Hoppa ur edit-mode
            BindData();
        }

        /// <summary>
        /// Hämta Data från Cache och bind till GridView
        /// </summary>
        private void BindData()
        {
            gridOrders.DataSource = Cache.Get("Products");
            gridOrders.DataBind();
        }

        /// <summary>
        /// När Produkterna försvinner från Cache, hämta dom igen.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="cacheItem"></param>
        /// <param name="reason"></param>
        private void OnRemove(string key, object cacheItem, CacheItemRemovedReason reason)
        {
            Cache.Insert("Products", Functions.GetProducts(), null, Cache.NoAbsoluteExpiration, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(OnRemove));
        }
    }
}